module.exports = options => {
  const assert = require('http-assert')
  const jwt = require('jsonwebtoken')
  const AdminUser = require('../models/AdminUser')
  const User = require("../models/User")
  var ok = require('assert')

  return async (req, res, next) => {
    let tokenData = String(req.headers.authorization || '').split(' ')
    const beCheckouTidentity = tokenData.pop()
    const token = tokenData.pop()
    assert(token, 401, '请先登录')
    const {
      _id,
      identity
    } = jwt.verify(token, req.app.get('secret'))
    assert(_id, 401, '请先登录')
    if (identity == 0 || identity == 1) {
      req.user = await User.findById(_id)
    } else if (identity == 2) {
      req.user = await AdminUser.findById(_id)
    }
    assert(req.user && req.user.identity == beCheckouTidentity, 401, '请先登录')
    await next()
  }
}